/*
 * @lc app=leetcode.cn id=2165 lang=cpp
 *
 * [2165] 重排数字的最小值
 */

// @lc code=start
class Solution
{
public:
    long long smallestNumber(long long num)
    {
        if (num == 0)
            return 0;

        int isFlag = 1;
        if (num < 0)
        {
            isFlag = -1;
            num = -num;
        }

        int count[10] = {0};
        while (num)
        {
            count[num % 10]++;
            num /= 10;
        }

        long long ans = 0;
        if (isFlag == 1)
        {
            for (int i = 1; i < 10; i++)
            {
                if (count[i] == 0)
                    continue;
                ans = i;
                count[i]--;
                break;
            }
        }

        int i = isFlag == 1 ? 0 : 9;
        int n = 9 - i;
        for (; i * isFlag <= n; i += isFlag)
        {
            for (int j = 0; j < count[i]; j++)
            {
                ans = ans * 10 + i;
            }
        }

        return isFlag == 1 ? ans : -ans;
    }
};
// @lc code=end
